#[macro_use]
extern crate actix_web;
extern crate log;
extern crate env_logger;
extern crate chrono;
#[macro_use]
extern crate lazy_static;

use std::{collections::HashMap, sync::Mutex, thread, time::Duration};
use std::sync::Arc;

use actix_web::{App, HttpServer};
use log::info;
use endpoints::*;
use nacos::nacos_query::Host;

mod endpoints;
mod nacos;
mod domain;
mod service;

static NACOS_SERVER: &str = "http://120.24.162.22:8848/nacos";
static PROVIDER_NAME: &str = "match-engine-service";
static PROVIDER_HOST: &str= "127.0.0.1";
static PROVIDER_PORT: u32=7878;

lazy_static!{
    static ref DP_SERVICES: Arc<Mutex<HashMap<&'static str,Host>>> = {
        let service_map = HashMap::new();
        let result = Arc::new(Mutex::new(service_map));
        result
    };
}

#[actix_rt::main]
async fn main()->std::io::Result<()>{
    // std::env::set_var("RUST_LOG", "actix_server=debug,actix_web=debug");
    // env_logger::init();
    init_log();

    nacos::nacos_query::query_instance_list("market-pusher").await;
    
    info!("Rust Actix Server running... http://localhost:7878/");
    nacos::register_service();
    nacos::ping_schedule();
    thread::sleep(Duration::from_secs(1));
    info!("instanceList is:{:?}",DP_SERVICES.lock().unwrap());
    HttpServer::new(|| App::new()
        .service(index)
        .service(add_order)
    )
    .bind("127.0.0.1:7878")?
    .run()
    .await
    
}


fn init_log() {
    use chrono::Local;
    use std::io::Write;
 
    let env = env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info");
    env_logger::Builder::from_env(env)
        .format(|buf, record| {
            writeln!(
                buf,
                "{} {} [{}:{}] {}",
                Local::now().format("%Y-%m-%d %H:%M:%S"),
                record.level(),
                record.module_path().unwrap_or("<unnamed>"),
                record.line().unwrap_or(0),
                &record.args()
            )
        })
        .init();
 
    info!("env_logger initialized.");
}